/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.easyjava.util;

import java.math.BigDecimal;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.node.ObjectNode;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

/**
 *
 * @author 朱雀
 */
public class XMLUtil {

	public static ObjectNode encode(String xmlString) {
		Document doc = null;
		ObjectNode nodeMap = null;
		try {
			doc = DocumentHelper.parseText(xmlString);
			Element root = doc.getRootElement();
			nodeMap = (ObjectNode) encodeNode(root);
		} catch (DocumentException ex) {
			Logger.getLogger(XMLUtil.class.getName()).log(Level.SEVERE, null, ex);
		}
		return nodeMap;
	}

	private static Object encodeNode(Element root) {
		Iterator it = root.elementIterator();
		if (it.hasNext()) {
			ObjectNode thisNode = JacksonNode.getMapper().createObjectNode();
			while (it.hasNext()) {
				Element node = (Element) it.next();
				Object nodeObject = encodeNode(node);
				if (nodeObject instanceof JsonNode) {
					thisNode.put(root.getName(), (JsonNode) nodeObject);
				} else if (nodeObject instanceof Integer) {
					thisNode.put(root.getName(), (Integer) nodeObject);
				} else if (nodeObject instanceof Long) {
					thisNode.put(root.getName(), (Long) nodeObject);
				} else if (nodeObject instanceof Float) {
					thisNode.put(root.getName(), (Float) nodeObject);
				} else if (nodeObject instanceof Double) {
					thisNode.put(root.getName(), (Double) nodeObject);
				} else if (nodeObject instanceof BigDecimal) {
					thisNode.put(root.getName(), (BigDecimal) nodeObject);
				} else if (nodeObject instanceof Boolean) {
					thisNode.put(root.getName(), (Boolean) nodeObject);
				} else {
					thisNode.put(root.getName(), (String) nodeObject);
				}
			}
			return thisNode;
		} else {
			return root.getData();
		}
	}
}
